#include <QtCore/QCoreApplication>
#include <windows.h>
#include <CommCtrl.h>
// 函数声明

#include <iostream>
#include <string>

bool AddRightClickMenu(const std::string& menuName, const std::string& applicationPath) {
    HKEY hKey;
    LONG result;
    DWORD dwDisposition;
    std::string menuKey = "*\\shell\\" + menuName;
    std::string cmdKey = menuKey + "\\command";

    // 创建菜单项键
    result = RegCreateKeyExA(HKEY_CLASSES_ROOT, menuKey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisposition);
    if (result != ERROR_SUCCESS) {
        std::cerr << "Failed to create menu key." << std::endl;
        return false;
    }
    // 设置菜单项的显示名称
    std::string menuDisplayName = menuName;
    result = RegSetValueExA(hKey, NULL, 0, REG_SZ, (const BYTE*)menuDisplayName.c_str(), menuDisplayName.length());
    if (result != ERROR_SUCCESS) {
        std::cerr << "Failed to set menu name." << std::endl;
        RegCloseKey(hKey);
        return false;
    }
    RegCloseKey(hKey);

    // 创建命令键
    result = RegCreateKeyExA(HKEY_CLASSES_ROOT, cmdKey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisposition);
    if (result != ERROR_SUCCESS) {
        std::cerr << "Failed to create command key." << std::endl;
        return false;
    }
    // 设置命令，注意路径中的引号用于处理路径中的空格，"%1"传递文件路径
    std::string command = "\"" + applicationPath + "\" \"%1\"";
    result = RegSetValueExA(hKey, NULL, 0, REG_SZ, (const BYTE*)command.c_str(), command.length());
    if (result != ERROR_SUCCESS) {
        std::cerr << "Failed to set command." << std::endl;
        RegCloseKey(hKey);
        return false;
    }
    RegCloseKey(hKey);

    std::cout << "Right-click menu item added successfully!" << std::endl;
    return true;
}




int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    // 启用自动排列图标
  // SetAutoArrange(true);

    // 禁用自动排列图标
    if (AddRightClickMenu("用我的记事本打开", "C:\\Windows\\System32\\notepad.exe")) {
        std::cout << "Success! Try right-clicking a file now." << std::endl;
    }
    else {
        std::cerr << "Failed to add menu item." << std::endl;
    }

    return app.exec();
}
